package com.example.demo.zhoushengwen.service.impl;

import com.example.demo.Dao.ExceptionLogRepository;
import com.example.demo.Entity.ExceptionLogExt;
import com.example.demo.zhoushengwen.service.ExceptionLogExtService;
import com.example.demo.zhoushengwen.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Service
public class RedisServiceImpl implements RedisService {
    @Autowired
    private RedisTemplate redisTemplate;

    //region 登录失败次数处理
    private final String KEY_LOGIN_FAIL_LIMIT = "login_fail_limit:%s";

    /**
     * 删除ip次数
     * @param ip
     */
    @Override
    public void deleteLoginFaildLimit(String ip) {
        String key = String.format(KEY_LOGIN_FAIL_LIMIT, ip);
        redisTemplate.delete(key);
    }
    /**
     * 查询ip次数
     * @param ip
     * @return
     */

    @Override
    public int getLoginFaildLimit(String ip) {
        String key = String.format(KEY_LOGIN_FAIL_LIMIT, ip);
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null)
            return 0;
        return Integer.parseInt(obj.toString());
    }


    /**
     * 添加ip次数（1分钟）
     * @param ip
     * @return
     */
    @Override
    public int addLoginFailLimit(String ip) {
        String key = String.format(KEY_LOGIN_FAIL_LIMIT, ip);
        Long newCount = redisTemplate.opsForValue().increment(key, 1);
        redisTemplate.expire(key, 1, TimeUnit.MINUTES);
        return newCount.intValue();
    }
}
